import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:photo_pipeline/photo_pipeline.dart';
import '../constants/colors.dart';
import '../constants/spacing.dart';
import '../constants/dimensions.dart';
import '../constants/text_styles.dart';
import '../mock_data/mock_data.dart';
import '../models/ai_pick_settings.dart';
import '../screens/tutorial_screen.dart';
import '../screens/ai_pick_settings_screen.dart';
import '../screens/camera_history_screen.dart';
import '../screens/photo_viewer_screen.dart';
import '../widgets/photo_grid_item.dart';
import '../widgets/base64_cached_image.dart';
import '../providers/pipeline_providers.dart';

enum ViewMode { list, grid2, grid3 }

/// 首页 - 相机连接
///
/// 显示上传统计信息（按状态分类的Tab）、图片列表和导入按钮
class HomeScreen extends ConsumerStatefulWidget {
  const HomeScreen({super.key});

  @override
  ConsumerState<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends ConsumerState<HomeScreen> {
  final Set<int> _selectedIds = <int>{};
  int _selectedStatusFilter = -1; // -1=全部, 0=待挑, 1=上传中, 2=已上传, 3=失败
  ViewMode _viewMode = ViewMode.list; // 当前视图模式
  bool _showTimeline = false; // 是否显示时间轴
  late final ScrollController _scrollController;
  bool _isLoadingMore = false;
  int? _initialPageSize;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController()..addListener(_onScroll);
    // 自动触发连接（在下一帧执行，确保 Widget 已构建完成）
    // 注意：pipelineConnectActionProvider 内部会调用 autoConnect
    Future.microtask(() {
      if (mounted) {
        // 触发自动连接，不等待结果（异步执行）
        ref.read(pipelineConnectActionProvider.future).catchError((error) {
          // 静默处理错误，避免未处理的异常
          debugPrint('[HomeScreen] 自动连接失败: $error');
        });
      }
    });
  }

  @override
  void dispose() {
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    super.dispose();
  }

  // 根据选中的状态筛选照片（直接订阅 Provider 数据）
  List<EnhancedFileInfo> get _filteredPhotos {
    final page = ref.watch(enhancedFirstPageProvider);
    return page.maybeWhen(
      data: (p) => p.data,
      orElse: () => const <EnhancedFileInfo>[],
    );
  }

  int get _selectedCount => _selectedIds.length;
  bool get _hasSelection => _selectedCount > 0;
  bool get _isAllSelected =>
      _filteredPhotos.isNotEmpty &&
      _filteredPhotos.every(
          (f) => f.fileInfo.id != null && _selectedIds.contains(f.fileInfo.id));

  /// 按日期和30分钟时间段分组照片
  Map<String, Map<String, List<EnhancedFileInfo>>>
      get _groupedPhotosByTimeline {
    final grouped = <String, Map<String, List<EnhancedFileInfo>>>{};

    for (final file in _filteredPhotos) {
      // 格式化日期：今天/昨天/具体日期
      final now = DateTime.now();
      final photoDate = file.fileInfo.createdAt ?? DateTime.now();
      final dateKey = _formatDateKey(now, photoDate);

      // 计算30分钟时间段
      final hour = photoDate.hour;
      final minute = photoDate.minute;
      final timeSlotMinute = minute < 30 ? 0 : 30;
      final timeKey =
          '${hour.toString().padLeft(2, '0')}:${timeSlotMinute.toString().padLeft(2, '0')}';

      grouped.putIfAbsent(dateKey, () => {});
      grouped[dateKey]!.putIfAbsent(timeKey, () => []);
      grouped[dateKey]![timeKey]!.add(file);
    }

    return grouped;
  }

  /// 格式化日期标签
  String _formatDateKey(DateTime now, DateTime date) {
    final today = DateTime(now.year, now.month, now.day);
    final photoDay = DateTime(date.year, date.month, date.day);
    final difference = today.difference(photoDay).inDays;

    if (difference == 0) {
      return '今天 ${date.month}月${date.day}日';
    } else if (difference == 1) {
      return '昨天 ${date.month}月${date.day}日';
    } else if (difference == 2) {
      return '前天 ${date.month}月${date.day}日';
    } else {
      return '${date.year}年${date.month}月${date.day}日';
    }
  }

  /// 格式化时间段标签
  String _formatTimeSlotLabel(String timeKey) {
    final parts = timeKey.split(':');
    final hour = int.parse(parts[0]);
    final minute = int.parse(parts[1]);

    final endHour = minute == 30 ? hour + 1 : hour;
    final endMinute = minute == 30 ? 0 : 30;

    return '$timeKey ~ ${endHour.toString().padLeft(2, '0')}:${endMinute.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    ref.listen<AsyncValue<PageData<EnhancedFileInfo>>>(
      enhancedFirstPageProvider,
      (previous, next) {
        next.whenData((pageData) {
          _initialPageSize ??= pageData.pageSize;
          if (_isLoadingMore && mounted) {
            setState(() {
              _isLoadingMore = false;
            });
          }
        });
      },
    );
    // 直接订阅首屏分页数据（不做本地镜像）
    final page = ref.watch(enhancedFirstPageProvider);

    final stats = MockData.uploadStats;

    return Scaffold(
      backgroundColor: AppColors.background,
      body: SafeArea(
        child: Stack(
          children: [
            // 主内容区
            Column(
              children: [
                // 顶部导航栏
                _buildTopNavBar(context),
                _buildConnectionBanner(),

                // 中间内容区（白色半透明背景）
                Expanded(
                  child: Container(
                    decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          Color(0x1FFFFFFF),
                          Color(0x0FFFFFFF),
                        ],
                      ),
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(16),
                        topRight: Radius.circular(16),
                      ),
                    ),
                    child: Column(
                      children: [
                        const SizedBox(height: AppSpacing.md),

                        // 第一行：全部统计 + 缓存信息 + 搜索图标
                        _buildTopRow(page),

                        const SizedBox(height: AppSpacing.md),

                        // 第二行：状态Tab栏（可点击切换）
                        _buildStatusTabs(stats),

                        const SizedBox(height: AppSpacing.md),

                        // 第三行：筛选/排序/时间轴/全选操作栏
                        _buildActionButtons(),

                        const SizedBox(height: AppSpacing.md),

                        // 图片列表或空状态（带时间轴侧边栏）
                        Expanded(
                          child: _filteredPhotos.isEmpty
                              ? _buildEmptyState()
                              : Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    // 时间轴侧边栏（120宽）
                                    if (_showTimeline)
                                      Container(
                                        width: 120,
                                        margin: const EdgeInsets.only(
                                          left: AppSpacing.md,
                                          right: AppSpacing.sm,
                                        ),
                                        child: _buildTimelineSidebar(),
                                      ),
                                    // 图片内容区域
                                    Expanded(
                                      child: _buildPhotoContent(),
                                    ),
                                  ],
                                ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),

            // 底部渐变遮罩
            if (_filteredPhotos.isNotEmpty)
              Positioned(
                left: 0,
                right: 0,
                bottom: 0,
                child: Container(
                  height: 94,
                  decoration: const BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Color(0x00000000),
                        Color(0xFF000000),
                      ],
                    ),
                  ),
                ),
              ),

            // 底部导入按钮（仅在没有选择时显示）
            if (!_hasSelection)
              Positioned(
                right: 16,
                bottom: _filteredPhotos.isNotEmpty ? 94 : 16,
                child: _buildImportButton(context),
              ),

            // 底部操作栏（仅在有照片且没有选择时显示）
            if (_filteredPhotos.isNotEmpty && !_hasSelection)
              Positioned(
                left: 43,
                right: 43,
                bottom: 22,
                child: _buildBottomActionBar(),
              ),

            // 底部上传菜单栏（仅在多选状态下显示）
            if (_hasSelection)
              Positioned(
                left: 43,
                right: 43,
                bottom: 22,
                child: _buildSelectionBottomBar(),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildConnectionBanner() {
    final connectStatus = ref.watch(pipelineConnectStatusProvider);
    return connectStatus.when(
      data: (status) {
        final isConnected = status is Connected && status.deviceInfo != null;
        final isConnecting = status is Connecting;
        final deviceName =
            isConnected ? status.deviceInfo?.model ?? '未知设备' : '未识别设备';
        final label = () {
          if (isConnecting) return '正在自动检测并连接相机...';
          if (isConnected) return '已连接 $deviceName';
          if (status is Disconnected && status.errorMessage != null) {
            return '连接失败：${status.errorMessage}';
          }
          return '未连接 - 点击连接将自动检测 USB 相机';
        }();
        return Padding(
          padding: const EdgeInsets.symmetric(
            horizontal: AppSpacing.md,
            vertical: AppSpacing.sm,
          ),
          child: Row(
            children: [
              Icon(
                isConnected ? Icons.camera_alt : Icons.camera_alt_outlined,
                color: isConnected ? Colors.greenAccent : Colors.orangeAccent,
                size: 20,
              ),
              const SizedBox(width: AppSpacing.sm),
              Expanded(
                child: Text(
                  label,
                  style: AppTextStyles.body1.copyWith(
                    color: AppColors.textPrimary,
                  ),
                ),
              ),
              TextButton.icon(
                onPressed: isConnecting
                    ? null
                    : () {
                        // 触发自动连接（使用 connectWithDetector）
                        ref.read(pipelineConnectActionProvider.future);
                      },
                icon: Icon(
                  isConnected ? Icons.refresh : Icons.link,
                  size: 18,
                ),
                label: Text(isConnected ? '重新连接' : '自动连接'),
              ),
            ],
          ),
        );
      },
      loading: () => Padding(
        padding: const EdgeInsets.symmetric(
          horizontal: AppSpacing.md,
          vertical: AppSpacing.sm,
        ),
        child: Row(
          children: const [
            SizedBox(
              width: 18,
              height: 18,
              child: CircularProgressIndicator(strokeWidth: 2),
            ),
            SizedBox(width: AppSpacing.sm),
            Text('正在初始化连接...'),
          ],
        ),
      ),
      error: (err, _) => Padding(
        padding: const EdgeInsets.symmetric(
          horizontal: AppSpacing.md,
          vertical: AppSpacing.sm,
        ),
        child: Row(
          children: [
            const Icon(Icons.error_outline, color: Colors.redAccent, size: 20),
            const SizedBox(width: AppSpacing.sm),
            Expanded(
              child: Text(
                '连接状态获取失败：$err',
                style: AppTextStyles.body2.copyWith(color: Colors.redAccent),
              ),
            ),
            TextButton(
              onPressed: () {
                final _ = ref.refresh(pipelineConnectStatusProvider);
              },
              child: const Text('重试'),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavBar(BuildContext context) {
    // 如果有选择，显示选择模式的导航栏
    if (_hasSelection) {
      return Container(
        height: 44,
        padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
        child: Row(
          children: [
            // 左边：取消选择按钮
            GestureDetector(
              onTap: () {
                setState(() {
                  _selectedIds.clear();
                });
              },
              child: Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: AppColors.cardBackground,
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Text(
                  '取消',
                  style: AppTextStyles.body2.copyWith(
                    color: AppColors.textPrimary,
                  ),
                ),
              ),
            ),

            const Spacer(),

            // 中间：选择的数量
            Text(
              '已选择 $_selectedCount',
              style: AppTextStyles.heading3.copyWith(
                color: AppColors.textPrimary,
              ),
            ),

            const Spacer(),

            // 右边：全选/取消全选按钮
            GestureDetector(
              onTap: _toggleSelectAll,
              child: Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: _isAllSelected
                      ? AppColors.cardBackground
                      : AppColors.primary,
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Text(
                  _isAllSelected ? '取消全选' : '全选',
                  style: AppTextStyles.body2.copyWith(
                    color:
                        _isAllSelected ? AppColors.textPrimary : Colors.white,
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    }

    final uploadStrategy = ref.watch(uploadStrategyProvider).maybeWhen(
          data: (value) => value,
          orElse: () => UploadStrategy.manual,
        );

    // 默认导航栏
    return Container(
      height: 44,
      padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      child: Row(
        children: [
          // 返回按钮（占位）
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              color: AppColors.cardBackground,
              borderRadius: BorderRadius.circular(60),
            ),
            child: const Icon(
              Icons.arrow_back_ios_new,
              size: 16,
              color: AppColors.textPrimary,
            ),
          ),

          const SizedBox(width: AppSpacing.sm),

          // "上传至:" 文本 + FTP图标（点击弹出面板）
          GestureDetector(
            onTap: () => _showConnectionPanel(context),
            child: Container(
              padding: const EdgeInsets.symmetric(
                horizontal: 8,
                vertical: 2,
              ),
              decoration: BoxDecoration(
                color: AppColors.cardBackground,
                borderRadius: BorderRadius.circular(20),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    width: 28,
                    height: 24,
                    decoration: BoxDecoration(
                      color: AppColors.cardBackgroundLight,
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: const Icon(
                      Icons.camera_alt,
                      size: 16,
                      color: AppColors.textSecondary,
                    ),
                  ),
                  const SizedBox(width: 12),
                  const Icon(
                    Icons.expand_more,
                    size: 12,
                    color: AppColors.textPrimary,
                  ),
                ],
              ),
            ),
          ),

          const Spacer(),

          // 教程按钮
          IconButton(
            padding: EdgeInsets.zero,
            constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
            icon: Container(
              width: 32,
              height: 32,
              decoration: BoxDecoration(
                color: AppColors.cardBackground,
                borderRadius: BorderRadius.circular(16),
              ),
              child: const Icon(
                Icons.help_outline,
                size: 18,
                color: AppColors.textPrimary,
              ),
            ),
            onPressed: () => showTutorialBottomSheet(context),
          ),

          const SizedBox(width: 8),

          // 上传策略选择器
          GestureDetector(
            onTap: () => _showUploadStrategySelector(context, uploadStrategy),
            child: Container(
              padding: const EdgeInsets.symmetric(
                horizontal: 8,
                vertical: 2,
              ),
              decoration: BoxDecoration(
                color: AppColors.cardBackground,
                borderRadius: BorderRadius.circular(20),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    _uploadStrategyLabel(uploadStrategy),
                    style: AppTextStyles.body2.copyWith(
                      color: AppColors.textPrimary,
                    ),
                  ),
                  const SizedBox(width: 4),
                  const Icon(
                    Icons.expand_more,
                    size: 16,
                    color: AppColors.textPrimary,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  String _uploadStrategyLabel(UploadStrategy strategy) {
    switch (strategy) {
      case UploadStrategy.manual:
        return '手动上传';
      case UploadStrategy.autoAfterCache:
        return '缓存后自动上传';
      case UploadStrategy.autoAfterAI:
        return 'AI 挑图后自动上传';
    }
  }

  /// 构建第一行：全部统计 + 缓存信息 + 搜索图标
  Widget _buildTopRow(AsyncValue<PageData<EnhancedFileInfo>> page) {
    // 从 page 中提取 total，如果加载中或错误则显示 0
    final totalCount = page.maybeWhen(
      data: (p) => p.total,
      orElse: () => 0,
    );

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      child: Row(
        children: [
          // 左侧：始终显示全部统计
          Text(
            '全部',
            style: AppTextStyles.heading3.copyWith(
              color: AppColors.textPrimary,
            ),
          ),
          const SizedBox(width: 4),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 6),
            decoration: BoxDecoration(
              color: AppColors.cardBackground,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Text(
              '$totalCount',
              style: AppTextStyles.caption.copyWith(
                fontWeight: FontWeight.w500,
                color: AppColors.textPrimary,
              ),
            ),
          ),

          const Spacer(),

          // 右侧：缓存信息
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
            decoration: BoxDecoration(
              color: AppColors.cardBackground,
              borderRadius: BorderRadius.circular(20),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  '100MB',
                  style: AppTextStyles.body2.copyWith(
                    color: AppColors.textPrimary,
                  ),
                ),
                const SizedBox(width: 10),
                const Icon(Icons.delete_outline,
                    size: 16, color: AppColors.textPrimary),
              ],
            ),
          ),

          const SizedBox(width: 12),

          // 搜索图标
          Container(
            width: 28,
            height: 28,
            decoration: BoxDecoration(
              color: AppColors.cardBackground,
              borderRadius: BorderRadius.circular(6),
            ),
            child: const Icon(Icons.search,
                size: 20, color: AppColors.textPrimary),
          ),
        ],
      ),
    );
  }

  /// 构建状态Tab栏（可点击切换，支持横向滚动，默认左对齐）
  Widget _buildStatusTabs(stats) {
    return Align(
      alignment: Alignment.centerLeft,
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            GestureDetector(
              onTap: () => _changeStatusFilter(0),
              child: _buildTabItem('待挑', stats.pendingCount,
                  isActive: _selectedStatusFilter == 0),
            ),
            const SizedBox(width: 12),
            GestureDetector(
              onTap: () => _changeStatusFilter(1),
              child: _buildTabItem('上传中', stats.uploadingCount,
                  isActive: _selectedStatusFilter == 1),
            ),
            const SizedBox(width: 12),
            GestureDetector(
              onTap: () => _changeStatusFilter(2),
              child: _buildTabItem('已上传', stats.uploadedCount,
                  isActive: _selectedStatusFilter == 2),
            ),
            const SizedBox(width: 12),
            GestureDetector(
              onTap: () => _changeStatusFilter(3),
              child: _buildTabItem('失败', stats.failedCount,
                  isActive: _selectedStatusFilter == 3),
            ),
          ],
        ),
      ),
    );
  }

  /// 切换状态筛选并清空选中
  void _changeStatusFilter(int newFilter) {
    setState(() {
      // 如果点击的是当前已选中的Tab，则取消选中（显示全部）
      if (_selectedStatusFilter == newFilter) {
        _selectedStatusFilter = -1; // -1表示全部
      } else {
        _selectedStatusFilter = newFilter;
      }

      // 清空所有选中
      _selectedIds.clear();
    });
    _resetPaginationAndScroll();
  }

  /// 构建单个Tab项
  Widget _buildTabItem(String label, int count, {bool isActive = false}) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: isActive ? const Color(0x33FFFFFF) : const Color(0x0DFFFFFF),
        borderRadius: BorderRadius.circular(AppDimensions.radiusXs),
      ),
      child: Text(
        '$label $count',
        style: AppTextStyles.caption.copyWith(color: AppColors.textSecondary),
        textAlign: TextAlign.center,
      ),
    );
  }

  /// 构建操作按钮行
  Widget _buildActionButtons() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      child: Row(
        children: [
          // 时间轴按钮（可点击切换显示/隐藏）
          GestureDetector(
            onTap: () => setState(() => _showTimeline = !_showTimeline),
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
              decoration: BoxDecoration(
                color: _showTimeline
                    ? AppColors.primary
                    : AppColors.cardBackground,
                borderRadius: BorderRadius.circular(14),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    '时间轴',
                    style: AppTextStyles.body2.copyWith(
                      color:
                          _showTimeline ? Colors.white : AppColors.textPrimary,
                    ),
                  ),
                  const SizedBox(width: 4),
                  Icon(
                    _showTimeline
                        ? Icons.keyboard_arrow_up
                        : Icons.keyboard_arrow_down,
                    size: 16,
                    color: _showTimeline ? Colors.white : AppColors.textPrimary,
                  ),
                ],
              ),
            ),
          ),

          const Spacer(),

          // 排序按钮（点击弹出选项）
          Opacity(
            opacity: 0.4,
            child: GestureDetector(
              onTap: _showSortOptions,
              child: _buildIconTextButton(Icons.sort, '排序'),
            ),
          ),

          const SizedBox(width: 8),

          // 筛选
          Opacity(
            opacity: 0.4,
            child: _buildIconTextButton(Icons.filter_list, '筛选'),
          ),

          const SizedBox(width: 8),

          // 全选（图标根据状态变化）
          Opacity(
            opacity: 0.4,
            child: GestureDetector(
              onTap: _toggleSelectAll,
              child: _buildIconTextButton(
                _isAllSelected
                    ? Icons.check_box
                    : Icons.check_box_outline_blank,
                '全选',
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 弹出排序选项
  void _showSortOptions() {
    showModalBottomSheet(
      context: context,
      backgroundColor: const Color(0xFF1C1C1E), // 深灰色，更容易区分边界
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) => Container(
        padding: const EdgeInsets.all(AppSpacing.lg),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              '选择布局',
              style:
                  AppTextStyles.heading3.copyWith(color: AppColors.textPrimary),
            ),
            const SizedBox(height: AppSpacing.lg),
            ListTile(
              leading:
                  const Icon(Icons.view_agenda, color: AppColors.textPrimary),
              title: Text('列表',
                  style: AppTextStyles.body1
                      .copyWith(color: AppColors.textPrimary)),
              trailing: _viewMode == ViewMode.list
                  ? const Icon(Icons.check, color: AppColors.primary)
                  : null,
              onTap: () {
                setState(() => _viewMode = ViewMode.list);
                Navigator.pop(context);
              },
            ),
            ListTile(
              leading:
                  const Icon(Icons.grid_view, color: AppColors.textPrimary),
              title: Text('网格 (2列)',
                  style: AppTextStyles.body1
                      .copyWith(color: AppColors.textPrimary)),
              trailing: _viewMode == ViewMode.grid2
                  ? const Icon(Icons.check, color: AppColors.primary)
                  : null,
              onTap: () {
                setState(() => _viewMode = ViewMode.grid2);
                Navigator.pop(context);
              },
            ),
            ListTile(
              leading: const Icon(Icons.apps, color: AppColors.textPrimary),
              title: Text('网格 (3列)',
                  style: AppTextStyles.body1
                      .copyWith(color: AppColors.textPrimary)),
              trailing: _viewMode == ViewMode.grid3
                  ? const Icon(Icons.check, color: AppColors.primary)
                  : null,
              onTap: () {
                setState(() => _viewMode = ViewMode.grid3);
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );
  }

  /// 切换全选
  void _toggleSelectAll() {
    setState(() {
      final shouldSelectAll = !_isAllSelected;
      if (shouldSelectAll) {
        for (final f in _filteredPhotos) {
          if (f.fileInfo.id != null) _selectedIds.add(f.fileInfo.id!);
        }
      } else {
        for (final f in _filteredPhotos) {
          if (f.fileInfo.id != null) _selectedIds.remove(f.fileInfo.id);
        }
      }
    });
  }

  void _onScroll() {
    if (!_scrollController.hasClients) return;
    final position = _scrollController.position;
    if (position.pixels >= position.maxScrollExtent - 200) {
      final pageValue = ref.read(enhancedFirstPageProvider);
      final pageData = pageValue.maybeWhen(
        data: (p) => p,
        orElse: () => null,
      );
      if (pageData != null) {
        _attemptLoadMore(pageData);
      }
    }
  }

  void _attemptLoadMore(PageData<EnhancedFileInfo> pageData) {
    if (_isLoadingMore) return;
    final currentCount = pageData.data.length;
    if (currentCount == 0) return;
    if (currentCount < pageData.pageSize) return;
    final total = pageData.total;
    if (total > 0 && currentCount >= total) return;

    final basePageSize = _initialPageSize ?? pageData.pageSize;
    if (basePageSize <= 0) return;

    final coordinator = ref.read(enhancedFirstPageCoordinatorProvider);
    if (coordinator == null) return;

    int nextPageSize = pageData.pageSize + basePageSize;
    if (total > 0 && nextPageSize > total) {
      nextPageSize = total;
    }
    if (nextPageSize <= pageData.pageSize) return;

    setState(() {
      _isLoadingMore = true;
    });

    coordinator.updatePagination(
      (pagination) => pagination.copyWith(page: 1, pageSize: nextPageSize),
    );
  }

  void _resetPaginationAndScroll() {
    _isLoadingMore = false;
    final pageValue = ref.read(enhancedFirstPageProvider);
    final initialSize = _initialPageSize ??
        pageValue.maybeWhen(
          data: (p) => p.pageSize,
          orElse: () => null,
        ) ??
        20;
    final coordinator = ref.read(enhancedFirstPageCoordinatorProvider);
    coordinator?.updatePagination(
      (pagination) => pagination.copyWith(page: 1, pageSize: initialSize),
    );
    if (_scrollController.hasClients) {
      _scrollController.jumpTo(0);
    }
  }

  /// 构建图标+文本按钮
  Widget _buildIconTextButton(IconData icon, String text) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 16, color: AppColors.textPrimary),
          const SizedBox(width: 4),
          Text(text,
              style:
                  AppTextStyles.body2.copyWith(color: AppColors.textPrimary)),
        ],
      ),
    );
  }

  Widget _buildStatusChip(EnhancedFileInfoStatus status) {
    final color = _statusColor(status);
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.16),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withOpacity(0.4)),
      ),
      child: Text(
        _statusLabel(status),
        style: AppTextStyles.caption.copyWith(
          color: color,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  String _statusLabel(EnhancedFileInfoStatus status) {
    switch (status) {
      case EnhancedFileInfoStatus.none:
        return '未缓存';
      case EnhancedFileInfoStatus.caching:
        return '缓存中';
      case EnhancedFileInfoStatus.cached:
        return '已缓存';
      case EnhancedFileInfoStatus.aiProcessing:
        return 'AI 处理中';
      case EnhancedFileInfoStatus.aiProcessed:
        return 'AI 已完成';
      case EnhancedFileInfoStatus.aiProcessFailed:
        return 'AI 失败';
      case EnhancedFileInfoStatus.aiProcessCancelled:
        return 'AI 已取消';
      case EnhancedFileInfoStatus.uploadPending:
        return '待上传';
      case EnhancedFileInfoStatus.uploading:
        return '上传中';
      case EnhancedFileInfoStatus.uploaded:
        return '已上传';
      case EnhancedFileInfoStatus.uploadFailed:
        return '上传失败';
      case EnhancedFileInfoStatus.uploadCancelled:
        return '上传已取消';
    }
  }

  Color _statusColor(EnhancedFileInfoStatus status) {
    switch (status) {
      case EnhancedFileInfoStatus.caching:
      case EnhancedFileInfoStatus.uploadPending:
        return AppColors.warning;
      case EnhancedFileInfoStatus.cached:
      case EnhancedFileInfoStatus.uploading:
        return AppColors.info;
      case EnhancedFileInfoStatus.aiProcessing:
        return AppColors.info;
      case EnhancedFileInfoStatus.aiProcessed:
      case EnhancedFileInfoStatus.uploaded:
        return AppColors.success;
      case EnhancedFileInfoStatus.aiProcessFailed:
      case EnhancedFileInfoStatus.uploadFailed:
        return AppColors.error;
      case EnhancedFileInfoStatus.aiProcessCancelled:
      case EnhancedFileInfoStatus.uploadCancelled:
        return AppColors.textSecondary;
      case EnhancedFileInfoStatus.none:
        return AppColors.textSecondary;
    }
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    String message;
    if (_selectedStatusFilter == -1) {
      message = '您还没有拍摄照片\n快去拍一张吧～';
    } else {
      final statusNames = ['待挑', '上传中', '已上传', '失败'];
      message = '暂无${statusNames[_selectedStatusFilter]}的照片';
    }

    return Center(
      child: Text(
        message,
        textAlign: TextAlign.center,
        style: AppTextStyles.body2.copyWith(
          color: AppColors.textPrimary.withOpacity(0.3),
        ),
      ),
    );
  }

  /// 构建图片内容（根据视图模式）
  Widget _buildPhotoContent() {
    switch (_viewMode) {
      case ViewMode.grid2:
        return _buildGridView(2);
      case ViewMode.grid3:
        return _buildGridView(3);
      case ViewMode.list:
        return _buildListView();
    }
  }

  /// 构建时间轴侧边栏（显示日期和时间段列表）
  Widget _buildTimelineSidebar() {
    final groupedPhotos = _groupedPhotosByTimeline;

    return Container(
      decoration: BoxDecoration(
        color: AppColors.cardBackground,
        borderRadius: BorderRadius.circular(AppDimensions.radiusSm),
      ),
      child: ListView.builder(
        padding:
            const EdgeInsets.only(top: 8, bottom: 120), // 增加底部padding确保可以滚动到底
        itemCount: groupedPhotos.length,
        itemBuilder: (context, dateIndex) {
          final dateKey = groupedPhotos.keys.elementAt(dateIndex);
          final timeGroups = groupedPhotos[dateKey]!;

          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 日期标题
              Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: 8,
                  vertical: 6,
                ),
                child: Text(
                  dateKey,
                  style: const TextStyle(
                    fontSize: 11,
                    color: AppColors.textPrimary,
                    fontWeight: FontWeight.w600,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),

              // 时间段列表
              ...timeGroups.entries.map((timeEntry) {
                final timeKey = timeEntry.key;
                final photos = timeEntry.value;

                return InkWell(
                  onTap: () {
                    // TODO: 滚动到对应的照片位置
                  },
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 8,
                      vertical: 6,
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            _formatTimeSlotLabel(timeKey),
                            style: const TextStyle(
                              fontSize: 10,
                              color: AppColors.textSecondary,
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        const SizedBox(width: 3),
                        Text(
                          '${photos.length}',
                          style: const TextStyle(
                            fontSize: 10,
                            color: AppColors.textSecondary,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              }).toList(),

              const SizedBox(height: 8),
            ],
          );
        },
      ),
    );
  }

  /// 构建列表视图
  Widget _buildListView() {
    final itemCount = _filteredPhotos.length + (_isLoadingMore ? 1 : 0);
    return ListView.builder(
      padding: const EdgeInsets.only(
        left: AppSpacing.md,
        right: AppSpacing.md,
        bottom: 120,
      ),
      controller: _scrollController,
      itemCount: itemCount,
      itemBuilder: (context, index) {
        if (_isLoadingMore && index == itemCount - 1) {
          return const Padding(
            padding: EdgeInsets.symmetric(vertical: AppSpacing.sm),
            child: Center(
              child: SizedBox(
                height: 20,
                width: 20,
                child: CircularProgressIndicator(strokeWidth: 2),
              ),
            ),
          );
        }
        final file = _filteredPhotos[index];
        final key = file.fileInfo.id != null
            ? ValueKey<int>(file.fileInfo.id!)
            : ValueKey<String>(
                file.fileInfo.path ?? file.fileInfo.name ?? 'list_$index',
              );
        return Padding(
          key: key,
          padding: const EdgeInsets.only(bottom: AppSpacing.sm),
          child: _buildListItem(file),
        );
      },
    );
  }

  /// 构建网格视图
  Widget _buildGridView(int columns) {
    final itemCount = _filteredPhotos.length + (_isLoadingMore ? 1 : 0);
    return GridView.builder(
      padding: const EdgeInsets.only(
        left: AppSpacing.md,
        right: AppSpacing.md,
        bottom: 120,
      ),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: columns,
        crossAxisSpacing: AppSpacing.sm,
        mainAxisSpacing: AppSpacing.sm,
        childAspectRatio: 1,
      ),
      controller: _scrollController,
      itemCount: itemCount,
      itemBuilder: (context, index) {
        if (_isLoadingMore && index == itemCount - 1) {
          return const Center(
            child: SizedBox(
              height: 20,
              width: 20,
              child: CircularProgressIndicator(strokeWidth: 2),
            ),
          );
        }
        return _buildGridItem(_filteredPhotos[index]);
      },
    );
  }

  /// 构建列表项
  Widget _buildListItem(EnhancedFileInfo file) {
    final isSelected =
        file.fileInfo.id != null && _selectedIds.contains(file.fileInfo.id);
    final status = file.status;

    return GestureDetector(
      onTap: () {
        if (_hasSelection) {
          _toggleFileSelection(file);
        } else {
          _showPhotoViewerFromHome(file);
        }
      },
      child: Container(
        height: 64,
        decoration: BoxDecoration(
          color: const Color(0x0AFFFFFF),
          borderRadius: BorderRadius.circular(12),
        ),
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        child: Row(
          children: [
            // 缩略图
            Container(
              width: 48,
              height: 48,
              decoration: BoxDecoration(
                color: AppColors.cardBackground,
                borderRadius: BorderRadius.circular(8),
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Stack(
                  fit: StackFit.expand,
                  children: [
                    _buildThumbnailForListItem(file),
                    // AI 综合评分（居中显示）
                    if (file.aiProcessingStatus != null)
                      Positioned.fill(
                        child: Center(
                          child: Builder(
                            builder: (context) {
                              final score =
                                  file.aiProcessingStatus!.overallQuality * 100;
                              final color = _getScoreColor(score);
                              return Container(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 6, vertical: 3),
                                decoration: BoxDecoration(
                                  color: Colors.black.withOpacity(0.6),
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: Text(
                                  '${score.toStringAsFixed(0)}',
                                  style: TextStyle(
                                    color: color,
                                    fontSize: 10,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              );
                            },
                          ),
                        ),
                      ),
                  ],
                ),
              ),
            ),
            const SizedBox(width: 12),
            // 信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    file.fileInfo.name ?? '',
                    style: AppTextStyles.body1
                        .copyWith(color: AppColors.textPrimary),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    _formatSize(file.fileInfo.size ?? 0),
                    style: AppTextStyles.caption
                        .copyWith(color: AppColors.textSecondary),
                  ),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(right: 12),
              child: _buildStatusChip(status),
            ),
            // 选择框
            GestureDetector(
              onTap: () => _toggleFileSelection(file),
              child: Container(
                width: 20,
                height: 20,
                decoration: BoxDecoration(
                  color: isSelected ? AppColors.primary : Colors.transparent,
                  border: Border.all(
                    color: isSelected
                        ? AppColors.primary
                        : AppColors.textSecondary,
                    width: 2,
                  ),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: isSelected
                    ? const Icon(Icons.check, size: 14, color: Colors.white)
                    : null,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建网格项
  Widget _buildGridItem(EnhancedFileInfo file) {
    final isSelected =
        file.fileInfo.id != null && _selectedIds.contains(file.fileInfo.id);
    return PhotoGridItem(
      key: file.fileInfo.id != null
          ? ValueKey<int>(file.fileInfo.id!)
          : ValueKey<String>(file.fileInfo.path ?? file.fileInfo.name ?? ''),
      file: file,
      isSelected: isSelected,
      onTap: () {
        if (_hasSelection) {
          _toggleFileSelection(file);
        } else {
          _showPhotoViewerFromHome(file);
        }
      },
      onSelectToggle: () => _toggleFileSelection(file),
    );
  }

  /// 切换照片选择状态
  void _toggleFileSelection(EnhancedFileInfo file) {
    final id = file.fileInfo.id;
    if (id == null) return;
    setState(() {
      if (_selectedIds.contains(id)) {
        _selectedIds.remove(id);
      } else {
        _selectedIds.add(id);
      }
    });
  }

  /// 构建导入按钮
  Widget _buildImportButton(BuildContext context) {
    return GestureDetector(
      onTap: () => _showConnectionMethodSelector(context),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        decoration: BoxDecoration(
          color: AppColors.cardBackground,
          borderRadius: BorderRadius.circular(24),
          boxShadow: const [
            BoxShadow(
              color: Color(0x0FFFFFFF),
              offset: Offset(0, 2),
              blurRadius: 4,
              blurStyle: BlurStyle.inner,
            ),
            BoxShadow(
              color: Color(0x14FFFFFF),
              offset: Offset(0, -2),
              blurRadius: 4,
              blurStyle: BlurStyle.inner,
            ),
          ],
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.download, size: 20, color: AppColors.textPrimary),
            const SizedBox(width: 2),
            Text('导入',
                style:
                    AppTextStyles.body2.copyWith(color: AppColors.textPrimary)),
          ],
        ),
      ),
    );
  }

  /// 构建底部操作栏
  Widget _buildBottomActionBar() {
    return Container(
      height: 56,
      padding: const EdgeInsets.all(4),
      decoration: BoxDecoration(
        color: const Color(0x05FFFFFF),
        borderRadius: BorderRadius.circular(32),
        boxShadow: const [
          BoxShadow(
            color: Color(0x0FFFFFFF),
            offset: Offset(0, 2),
            blurRadius: 4,
            blurStyle: BlurStyle.inner,
          ),
          BoxShadow(
            color: Color(0x14FFFFFF),
            offset: Offset(0, -2),
            blurRadius: 4,
            blurStyle: BlurStyle.inner,
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _buildBottomIcon(Icons.camera_alt),
          _buildBottomIcon(Icons.photo_library),
          _buildBottomIcon(Icons.settings),
          _buildBottomIcon(
            Icons.cloud_upload,
            onTap: () => Navigator.pushNamed(context, '/upload-tasks'),
          ),
          _buildBottomIcon(Icons.folder_open),
        ],
      ),
    );
  }

  Widget _buildBottomIcon(IconData icon, {VoidCallback? onTap}) {
    return GestureDetector(
      onTap: onTap,
      behavior: HitTestBehavior.opaque,
      child: Container(
        width: 48,
        height: 48,
        decoration: BoxDecoration(
          color: Colors.transparent,
          borderRadius: BorderRadius.circular(24),
        ),
        child: Icon(icon, size: 24, color: AppColors.textSecondary),
      ),
    );
  }

  /// 构建多选状态下的底部菜单栏
  Widget _buildSelectionBottomBar() {
    return Container(
      height: 56,
      padding: const EdgeInsets.all(4),
      decoration: BoxDecoration(
        color: const Color(0x05FFFFFF),
        borderRadius: BorderRadius.circular(32),
        boxShadow: const [
          BoxShadow(
            color: Color(0x0FFFFFFF),
            offset: Offset(0, 2),
            blurRadius: 4,
            blurStyle: BlurStyle.inner,
          ),
          BoxShadow(
            color: Color(0x14FFFFFF),
            offset: Offset(0, -2),
            blurRadius: 4,
            blurStyle: BlurStyle.inner,
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 上传按钮
          GestureDetector(
            onTap: _uploadSelectedPhotos,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              decoration: BoxDecoration(
                color: AppColors.primary,
                borderRadius: BorderRadius.circular(24),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Icon(Icons.cloud_upload, size: 20, color: Colors.white),
                  const SizedBox(width: 8),
                  Text(
                    '上传 $_selectedCount 张',
                    style: AppTextStyles.body2.copyWith(
                      color: Colors.white,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 上传选中的照片
  Future<void> _uploadSelectedPhotos() async {
    final selectedIds = _selectedIds.toList();

    if (selectedIds.isEmpty) return;

    try {
      // 通过上传模块统一入队上传任务
      final controller = ref.read(pipelineControllerProvider);
      await controller.upload.enqueue(selectedIds);

      // 清空选择并显示提示
      setState(() => _selectedIds.clear());

      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('正在准备上传 ${selectedIds.length} 张照片')),
      );
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('上传失败: $e')),
      );
    }
  }

  /// 显示连接方式选择器
  void _showConnectionMethodSelector(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (context) => Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFF1F1F1F), Color(0xFF0F0F0F)],
          ),
          borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 拖拽手柄
            const SizedBox(height: 12),
            Container(
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(2),
              ),
            ),

            // 标题栏
            Container(
              height: 56,
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Stack(
                children: [
                  Center(
                    child: Text(
                      '导入照片',
                      style: AppTextStyles.heading3.copyWith(
                        color: Colors.white,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                  Positioned(
                    right: 0,
                    top: 0,
                    bottom: 0,
                    child: IconButton(
                      icon: Container(
                        width: 24,
                        height: 24,
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.06),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: const Icon(
                          Icons.close,
                          size: 16,
                          color: Colors.white,
                        ),
                      ),
                      onPressed: () => Navigator.pop(context),
                    ),
                  ),
                ],
              ),
            ),

            // 选项列表
            Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                children: [
                  _buildImportOption(
                    context,
                    title: '从读卡器选择上传',
                    subtitle: '从读卡器中选择照片进行上传',
                    icon: Icons.sd_card,
                    onTap: () {
                      Navigator.pop(context);
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('从读卡器选择上传功能开发中')),
                      );
                    },
                  ),
                  const SizedBox(height: 12),
                  _buildImportOption(
                    context,
                    title: '从相机历史上传',
                    subtitle: '从相机中选择已拍摄的照片上传',
                    icon: Icons.history,
                    onTap: () {
                      Navigator.pop(context);
                      _showCameraHistorySheet(context);
                    },
                  ),
                  const SizedBox(height: 12),
                  _buildImportOption(
                    context,
                    title: '从手机图库中选择上传',
                    subtitle: '选择手机本地相册中的图片进行上传',
                    icon: Icons.photo_library,
                    onTap: () {
                      Navigator.pop(context);
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('从手机图库选择上传功能开发中')),
                      );
                    },
                  ),
                ],
              ),
            ),

            const SizedBox(height: 16),
          ],
        ),
      ),
    );
  }

  Widget _buildImportOption(
    BuildContext context, {
    required String title,
    required String subtitle,
    required IconData icon,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.06),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Row(
          children: [
            Container(
              width: 16,
              height: 16,
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Icon(
                icon,
                size: 12,
                color: Colors.white,
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: AppTextStyles.body1.copyWith(
                      color: Colors.white,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    subtitle,
                    style: AppTextStyles.body2.copyWith(
                      color: Colors.white.withOpacity(0.3),
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 显示相机历史弹窗
  void _showCameraHistorySheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (context) => DraggableScrollableSheet(
        initialChildSize: 0.8,
        minChildSize: 0.5,
        maxChildSize: 0.95,
        builder: (context, scrollController) {
          return const CameraHistorySheet();
        },
      ),
    );
  }

  /// 从首页显示照片查看器
  void _showPhotoViewerFromHome(EnhancedFileInfo file) async {
    final fileId = file.fileInfo.id;
    if (fileId == null) return;

    // 1. 触发最高优先级下载（异步，不阻塞 UI）
    try {
      final controller = ref.read(pipelineControllerProvider);
      final fileInfo = file.fileInfo;
      // 使用最高优先级下载原图
      controller.camera.downloadEmergency(fileInfo).catchError((e, stack) {
        debugPrint('[HomeScreen] 下载原图失败: $e');
        return null;
      });
    } catch (e) {
      debugPrint('[HomeScreen] 下载原图失败: $e');
    }

    // 2. 订阅下载进度（数据驱动架构）
    // 注意：下载进度通过 fileCacheProgressProvider 在 PhotoViewerScreen 中订阅显示

    // 3. 准备照片列表和标题
    final List<String> photos =
        _filteredPhotos.map((f) => f.fileInfo.name ?? '').toList();
    final List<String> titles =
        _filteredPhotos.map((f) => f.fileInfo.name ?? '').toList();
    final List<int> fileIds =
        _filteredPhotos.map((f) => f.fileInfo.id).whereType<int>().toList();
    final int initialIndex =
        _filteredPhotos.indexWhere((f) => f.fileInfo.id == file.fileInfo.id);

    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => PhotoViewerScreen(
          photos: photos,
          initialIndex: initialIndex >= 0 ? initialIndex : 0,
          titles: titles,
          fileIds: fileIds,
        ),
      ),
    );
  }

  String _formatSize(int bytes) {
    if (bytes < 1024) return '$bytes B';
    if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(1)} KB';
    }
    return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
  }

  /// 根据分数获取颜色
  /// 90分以上（包含90）：紫色
  /// 75-90：蓝色
  /// 55-75：绿色
  /// 其他：白色
  Color _getScoreColor(double score) {
    if (score >= 90) {
      return Colors.purple;
    } else if (score >= 75) {
      return Colors.blue;
    } else if (score >= 55) {
      return Colors.green;
    } else {
      return Colors.white;
    }
  }

  /// 构建列表项缩略图（带缓存）
  Widget _buildThumbnailForListItem(EnhancedFileInfo file) {
    return Base64CachedImage(
      fileInfo: file.fileInfo,
      fit: BoxFit.cover,
      filterQuality: FilterQuality.low,
      placeholder: const Center(
        child: SizedBox(
          width: 16,
          height: 16,
          child: CircularProgressIndicator(strokeWidth: 1.5),
        ),
      ),
      errorWidget: const Center(
        child: Icon(
          Icons.broken_image_outlined,
          size: 24,
          color: AppColors.textSecondary,
        ),
      ),
    );
  }

  /// 获取上传规则文字
  String _getUploadRuleText() {
    // 从AI设置页面获取缓存的设置
    final settings = AIPickSettingsScreen.getCachedSettings();

    switch (settings.uploadRule) {
      case UploadRule.all:
        return '免挑图直接上传';
      case UploadRule.aiFiltered:
        return 'AI挑图自动上传';
      case UploadRule.manualSelection:
        return '人工审核上传';
    }
  }

  /// 显示连接面板
  void _showConnectionPanel(BuildContext context) {
    showGeneralDialog(
      context: context,
      barrierDismissible: true,
      barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
      barrierColor: const Color(0x66000000), // 半透明黑色遮罩
      transitionDuration: const Duration(milliseconds: 250),
      pageBuilder: (context, animation, secondaryAnimation) {
        return GestureDetector(
          onTap: () => Navigator.of(context).pop(),
          behavior: HitTestBehavior.opaque,
          child: SafeArea(
            child: Column(
              children: [
                // 导航栏区域，点击可关闭
                GestureDetector(
                  onTap: () => Navigator.of(context).pop(),
                  child: Container(
                    height: 44,
                    color: Colors.transparent,
                  ),
                ),
                // 面板内容
                GestureDetector(
                  onTap: () {}, // 阻止事件冒泡
                  child: Material(
                    color: Colors.transparent,
                    child: Container(
                      width: double.infinity,
                      decoration: BoxDecoration(
                        color: const Color(0xFF1B1B1B),
                        borderRadius: const BorderRadius.only(
                          bottomLeft: Radius.circular(20),
                          bottomRight: Radius.circular(20),
                        ),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.3),
                            blurRadius: 20,
                            offset: const Offset(0, 8),
                          ),
                        ],
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          // 顶部装饰线
                          Container(
                            height: 1,
                            color: const Color(0x1FFFFFFF),
                          ),

                          Padding(
                            padding: const EdgeInsets.all(16),
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              crossAxisAlignment: CrossAxisAlignment.stretch,
                              children: [
                                // 标题
                                Text(
                                  '相机连接指引',
                                  style: AppTextStyles.body2.copyWith(
                                    color: AppColors.textSecondary
                                        .withOpacity(0.3),
                                  ),
                                ),
                                const SizedBox(height: 12),

                                // 三个连接方式按钮
                                Row(
                                  children: [
                                    Expanded(
                                      child: _buildConnectionButton(
                                        context,
                                        '相机有线传输',
                                        Icons.usb,
                                      ),
                                    ),
                                    const SizedBox(width: 12),
                                    Expanded(
                                      child: _buildConnectionButton(
                                        context,
                                        '相机无线传输',
                                        Icons.wifi,
                                      ),
                                    ),
                                    const SizedBox(width: 12),
                                    Expanded(
                                      child: _buildConnectionButton(
                                        context,
                                        '相机FTP传输',
                                        Icons.router,
                                      ),
                                    ),
                                  ],
                                ),

                                const SizedBox(height: 16),

                                // AI挑图设置
                                _buildSettingItem(
                                  context,
                                  'AI挑图设置',
                                  _getUploadRuleText(),
                                  () {
                                    Navigator.pop(context);
                                    Navigator.pushNamed(context, '/ai-settings')
                                        .then((_) {
                                      // 从AI设置返回后刷新状态
                                      setState(() {});
                                    });
                                  },
                                ),

                                const SizedBox(height: 16),

                                // 相机连接传输设置
                                _buildSettingItem(
                                  context,
                                  '相机连接传输设置',
                                  null,
                                  () {
                                    Navigator.pop(context);
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      const SnackBar(content: Text('相机连接传输设置')),
                                    );
                                  },
                                ),

                                const SizedBox(height: 16),

                                // 缓存清理
                                _buildCacheItem(context),

                                const SizedBox(height: 16),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
      transitionBuilder: (context, animation, secondaryAnimation, child) {
        return FadeTransition(
          opacity: CurvedAnimation(
            parent: animation,
            curve: Curves.easeOut,
          ),
          child: SlideTransition(
            position: Tween<Offset>(
              begin: const Offset(0, -0.3),
              end: Offset.zero,
            ).animate(CurvedAnimation(
              parent: animation,
              curve: Curves.easeOutCubic,
            )),
            child: child,
          ),
        );
      },
    );
  }

  /// 构建连接方式按钮
  Widget _buildConnectionButton(
      BuildContext context, String title, IconData icon) {
    return GestureDetector(
      onTap: () {
        print('[PhotoPipeline] 开始自动连接：$title');
        // 使用自动连接逻辑（内部会使用 connectWithDetector）
        ref.read(pipelineConnectActionProvider.future).then((_) {
          Navigator.pop(context);
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('正在自动检测并连接相机...'),
              duration: const Duration(seconds: 2),
            ),
          );
        }).catchError((error) {
          Navigator.pop(context);
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('连接失败：$error'),
              backgroundColor: Colors.redAccent,
              duration: const Duration(seconds: 3),
            ),
          );
        });
      },
      child: Container(
        height: 90,
        decoration: BoxDecoration(
          color: AppColors.cardBackground,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Container(
              width: 32,
              height: 32,
              decoration: BoxDecoration(
                color: AppColors.cardBackground,
                borderRadius: BorderRadius.circular(16),
              ),
              child: Icon(icon, size: 16, color: AppColors.textSecondary),
            ),
            const SizedBox(height: 8),
            Text(
              title,
              style: AppTextStyles.body2.copyWith(
                color: AppColors.textPrimary,
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
          ],
        ),
      ),
    );
  }

  /// 构建设置项
  Widget _buildSettingItem(
    BuildContext context,
    String title,
    String? subtitle,
    VoidCallback onTap,
  ) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: const Color(0x12FFFFFF),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Row(
          children: [
            Text(
              title,
              style: AppTextStyles.body1.copyWith(
                color: AppColors.textPrimary,
              ),
            ),
            const Spacer(),
            if (subtitle != null)
              Text(
                subtitle,
                style: AppTextStyles.body2.copyWith(
                  color: AppColors.textSecondary.withOpacity(0.48),
                ),
              ),
            const SizedBox(width: 8),
            const Icon(
              Icons.arrow_forward_ios,
              size: 16,
              color: AppColors.textPrimary,
            ),
          ],
        ),
      ),
    );
  }

  /// 构建缓存清理项
  Widget _buildCacheItem(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.pop(context);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('缓存清理')),
        );
      },
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: const Color(0x12FFFFFF),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Row(
          children: [
            Text(
              '缓存清理',
              style: AppTextStyles.body1.copyWith(
                color: AppColors.textPrimary,
              ),
            ),
            const Spacer(),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              decoration: BoxDecoration(
                color: AppColors.cardBackground,
                borderRadius: BorderRadius.circular(20),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    '100MB',
                    style: AppTextStyles.body2.copyWith(
                      color: AppColors.textPrimary,
                    ),
                  ),
                  const SizedBox(width: 10),
                  const Icon(
                    Icons.close,
                    size: 16,
                    color: AppColors.textPrimary,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 显示上传策略选择器
  void _showUploadStrategySelector(
    BuildContext context,
    UploadStrategy current,
  ) {
    showModalBottomSheet(
      context: context,
      useSafeArea: true,
      backgroundColor: const Color(0xFF1B1B1B),
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) {
        final mediaQuery = MediaQuery.of(context);
        final bottomPadding = mediaQuery.viewInsets.bottom +
            mediaQuery.padding.bottom;

        return Padding(
          padding: EdgeInsets.only(bottom: bottomPadding),
          child: Container(
            padding: const EdgeInsets.all(16),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  '选择上传策略',
                  style: AppTextStyles.heading3.copyWith(
                    color: AppColors.textPrimary,
                  ),
                ),
                const SizedBox(height: 16),
                ...UploadStrategy.values.map((strategy) {
                  return ListTile(
                    leading: Icon(
                      current == strategy
                          ? Icons.radio_button_checked
                          : Icons.radio_button_off,
                      color: AppColors.textPrimary,
                      size: 20,
                    ),
                    title: Text(
                      _uploadStrategyLabel(strategy),
                      style: AppTextStyles.body1.copyWith(
                        color: AppColors.textPrimary,
                      ),
                    ),
                    onTap: () {
                      Navigator.pop(context);
                      final controller = ref.read(pipelineControllerProvider);
                      controller.upload.setStrategy(strategy);
                      if (!mounted) return;
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text(
                            '已切换至${_uploadStrategyLabel(strategy)}',
                          ),
                        ),
                      );
                    },
                  );
                }),
              ],
            ),
          ),
        );
      },
    );
  }
}
